﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Data.Model;
using ZLCMS.Commands.Data;
using Newtonsoft.Json;
using NHibernate.Criterion;

namespace ZLCMS.Web.Tools
{
    public partial class UpdateProductSupply : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string key = "FXPr8n1HGXlAKvyb";
            if (Request["key"] != key)
            {
                Response.Write("param error");
                return;
            }


            //
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                var skuList = session.CreateQuery(" from ShopSkuProduct where Status = '1' ").List<ShopSkuProduct>();

                ShopProductSupplyInfo supplyInfo;
                ShopProductInfo productInfo;

                int supplyCount;
                string skuString;

                foreach (var skuItem in skuList)
                {
                    supplyCount = Convert.ToInt32(session.CreateSQLQuery(" select count(1) from Shop_Product_Supply_Info where Product_Sku_Code = :skucode and status <> '9' ")
                                        .SetParameter("skucode", skuItem.ProductSkuCode)
                                        .UniqueResult());

                    if (supplyCount > 0)
                    {
                        continue;
                    }
                    else
                    {
                        List<SKUGroup> jlist = JsonConvert.DeserializeObject<List<SKUGroup>>(skuItem.ParamCode);

                        skuString = null;

                        foreach (var jitem in jlist)
                        {
                            skuString += jitem.ItemName + ",";
                        }

                        productInfo = session.CreateCriteria<ShopProductInfo>().Add(Expression.Eq("ProductNo", skuItem.ProductNo)).UniqueResult<ShopProductInfo>();

                        supplyInfo = new ShopProductSupplyInfo()
                        {
                            OptDate = DateTime.Now,
                            ProductNo = skuItem.ProductNo,
                            ProductName = skuItem.ProductSkuTitle,
                            ProductSkuCode = skuItem.ProductSkuCode,
                            ProductSkuName = skuString,
                            Status = "0",
                            DeptCode = productInfo.DeptCode
                        };
                        session.Save(supplyInfo);
                        session.Flush();
                    }
                }
            }
                        
            Response.Write("success");
        }
    }
}